/**
 * @file
 * @author dousha 
 * @date 2020/11/29.
 */

#include "buttons.h"
#include <stm32f1xx_hal.h>

static uint8_t button_state = BUTTON_NONE, last_button_state = BUTTON_NONE;

static uint32_t scanCount = 0;

static void (*button_callback)(uint8_t);

void buttons_init(void (*cb)(uint8_t)) {
	button_callback = cb;
}

void buttons_scan() {
	button_state = buttons_get_immediate_state();
	if (button_state == BUTTON_NONE && last_button_state != BUTTON_NONE) {
		button_callback(last_button_state);
		last_button_state = BUTTON_NONE;
	} else {
		if (button_state < last_button_state) {
			last_button_state = button_state;
		}
	}
	++scanCount;
}

uint8_t buttons_get_state() {
	return button_state;
}

uint32_t buttons_get_scan_count() {
	return scanCount;
}

uint8_t buttons_get_immediate_state() {
	uint8_t out = 0;
	if (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0)) {
		out |= 0b00000100u;
	} else {
		out &= 0b00000011u;
	}
	if (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_1)) {
		out |= 0b00000010u;
	} else {
		out &= 0b00000101u;
	}
	if (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_2)) {
		out |= 0b00000001u;
	} else {
		out &= 0b00000110u;
	}
	return out;
}
